package tw.twandroidproj.app.ui.fragment;



/**
 * Created by frezc on 2015/4/11.
 * Rewrite by Raymon on 2016
 * 主页的fragment
 */


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.utils.L;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.util.ArrayList;
import java.util.List;

import tw.twandroidproj.app.MyApp;
import tw.twandroidproj.app.R;
import tw.twandroidproj.app.model.Bean;
import tw.twandroidproj.app.model.ErrorModel;
import tw.twandroidproj.app.model.Job;
import tw.twandroidproj.app.network.AuthManager;
import tw.twandroidproj.app.network.NetworkManager;
import tw.twandroidproj.app.network.OnResponseListener;


import tw.twandroidproj.app.ui.BadgeActionProvider;
import tw.twandroidproj.app.ui.GlideImageLoader;
import tw.twandroidproj.app.ui.activity.LoginActivity;
import tw.twandroidproj.app.ui.activity.MessageActivity;
import tw.twandroidproj.app.ui.activity.SettingsActivity;
import tw.twandroidproj.app.ui.adapter.ReLayoutManager;
import tw.twandroidproj.app.ui.adapter.mainRecyclerview_Adapter;

public class MainFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
    /**
     * 当前轮询执行的时间间隔
     */
    private static int interval = 10*1000;
    /**
     * 轮询Handler的消息类型
     */
    private static int LOOP_WHAT = 10;

    private RecyclerView main_recycleview;
    private List<Job> mdata=new ArrayList<>();
    private Toolbar mtoolbar;
    private AppBarLayout appBarLayout;
    private CollapsingToolbarLayout mcollapsingtoolbarlayout;
    private NetworkManager jobNetwork;
    private AuthManager sms_authmanager;
    private int limit=20;
    private int offset;
    private List<Job> tempList = new ArrayList<>();
    private List<Integer> imgList=new ArrayList<>();

    private BadgeActionProvider mBadgeActionProvider;
    private MyApp mapp_mainFragment;
    private SwipeRefreshLayout mSwipRefreshLayout;
    private LinearLayoutManager mLayoutManager;
    private mainRecyclerview_Adapter adapter;
    private Banner banner;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_main_homepage, container, false);
        main_recycleview= (RecyclerView) layout.findViewById(R.id.main_recyclerview);
        LinearLayout location_view= (LinearLayout) layout.findViewById(R.id.location_main_toolabr);
        imgList.add(R.drawable.a1);
        imgList.add(R.drawable.a2);
        imgList.add(R.drawable.a3);
        imgList.add(R.drawable.a4);
        banner= (Banner) layout.findViewById(R.id.banner);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR	);
        banner.setImageLoader(new GlideImageLoader());
        banner.setImages(imgList);
        banner.setDelayTime(1500);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.start();
        location_view.setOnClickListener(new View.OnClickListener() {//toolbar左上方的位置信息展示，点击进入选择位置的activity
            @Override
            public void onClick(View v) {

            }
        });
        mBadgeActionProvider=new BadgeActionProvider(getContext());
        L.i("页面onStart，需要开启轮询");
        loopRequestHandler.sendEmptyMessageDelayed(LOOP_WHAT, interval);

        jobNetwork=NetworkManager.getInstance(this.getActivity());
        sms_authmanager=AuthManager.getInstance(this.getActivity());

        mtoolbar= (Toolbar) layout.findViewById(R.id.toolbar_main);
        ((AppCompatActivity) getActivity()).setSupportActionBar(mtoolbar);
        mcollapsingtoolbarlayout= (CollapsingToolbarLayout) layout.findViewById(R.id.mcollapsingtoolbarlayout);
        mcollapsingtoolbarlayout.setTitle("淘兼职");
        mcollapsingtoolbarlayout.setExpandedTitleColor(Color.TRANSPARENT);
        mcollapsingtoolbarlayout.setCollapsedTitleTextColor(Color.WHITE);
        mapp_mainFragment= (MyApp)getActivity(). getApplication();
        mSwipRefreshLayout= (SwipeRefreshLayout) layout.findViewById(R.id.main_srl);
        mSwipRefreshLayout.setOnRefreshListener(this);
        mSwipRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);
        mLayoutManager=new LinearLayoutManager(this.getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        main_recycleview.setLayoutManager(mLayoutManager);
        adapter=new mainRecyclerview_Adapter(getActivity());
        main_recycleview.setAdapter(adapter);
        main_recycleview.addOnScrollListener(mOnScrollListener);
        initData();

        return layout;
    }

    private void sms_refresh() {
        if(mapp_mainFragment.getSms_symbol().equals("1")){
            mBadgeActionProvider.setBadge(mapp_mainFragment.getSms_count());
            mapp_mainFragment.setSms_symbol("0");
        }else{

            mBadgeActionProvider.settextfail();
                }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);

   }

    /**
     * 处理轮询的Handler
     */
    private Handler loopRequestHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            L.i("轮询中-----当前轮询间隔：" + interval);
            loopRequestHandler.removeMessages(LOOP_WHAT);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    sms_refresh();
                }
            });
            System.gc();
            loopRequestHandler.sendEmptyMessageDelayed(LOOP_WHAT, interval);
        }
    };
//刷新的数据
    private void initData() {
        offset=0;
        mdata.clear();
        jobNetwork.getAllJob(limit,offset,new OnResponseListener<Bean<Job>>() {
            @Override
            public void onSuccess(Bean<Job> result) {
                mdata.addAll(result.getList());
                adapter.setData(mdata);

//                SugarRecord.deleteAll(Job.class);//感觉其实也不用存这个东西，没网显示个没网就好了，以后再说
//                Job job_save;
//                for(int i=0;i<result.getList().size();i++) {
//                    job_save=result.getList().get(i);
//                    SugarRecord.save(job_save);
//                }
            }

            @Override
            public void onFailed(ErrorModel errorModel) {

            }
        });
    }
//加载的数据
    private List<Job> getDataList(int size) {
        final List<Job> data=new ArrayList<Job>();
         data.clear();
         jobNetwork.getAllJob(limit,size,new OnResponseListener<Bean<Job>>() {
         @Override
         public void onSuccess(Bean<Job> result) {

             data.addAll(result.getList());

         }

         @Override
         public void onFailed(ErrorModel errorModel) {

         }
     });
         return data;
    }
    // RecyclerView的滑动监听事件
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener()
    {
        private int lastVisibleItem;

        // 滑动状态改变
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState)
        {
            super.onScrollStateChanged(recyclerView, newState);
            /**
             * scrollState有三种状态，分别是SCROLL_STATE_IDLE、SCROLL_STATE_TOUCH_SCROLL、SCROLL_STATE_FLING
             * SCROLL_STATE_IDLE是当屏幕停止滚动时
             * SCROLL_STATE_TOUCH_SCROLL是当用户在以触屏方式滚动屏幕并且手指仍然还在屏幕上时
             * SCROLL_STATE_FLING是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
             */
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == adapter.getItemCount()
                    && adapter.isShowFooter())
            {

                // 加载更多

                offset=mdata.size();
                Log.v("offset",String.valueOf(offset));
                tempList.clear();
                tempList = getDataList(offset);
                new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mdata.addAll(tempList);
                Log.v("offset",String.valueOf(mdata.size()));
                if(mdata.size() >= 100|mdata.size()==offset){
                    Toast.makeText(getActivity(),"没有更多内容了",Toast.LENGTH_SHORT).show();

                    return;

                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.setData(mdata);

                    }
                });
            }
        }, 2000);
            }
        }

        // 滑动位置
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            super.onScrolled(recyclerView, dx, dy);
            // 给lastVisibleItem赋值
            // findLastVisibleItemPosition()是返回最后一个item的位置
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
        }
    };

    /**
     * Toolbar自定义菜单，点击监听。
     */
    private BadgeActionProvider.OnClickListener onClickListener = new BadgeActionProvider.OnClickListener() {
        @Override
        public void onClick() {
            if(sms_authmanager.isLogined()) {
                startActivity(new Intent(getActivity(), MessageActivity.class));
//                mBadgeActionProvider.settextfail();
            }
            else{
                startActivity(new Intent(getActivity(),LoginActivity.class));
            }
        }
    };


    @Override
    public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.menu_main, menu);
        MenuItem menuItem = menu.findItem(R.id.message_toobar);
        mBadgeActionProvider = (BadgeActionProvider) MenuItemCompat.getActionProvider(menuItem);
        mBadgeActionProvider.setOnClickListener(onClickListener);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                if(mapp_mainFragment.getSms_count()=="0"){mBadgeActionProvider.settextfail();}
                else {
                    mBadgeActionProvider.setBadge(mapp_mainFragment.getSms_count());
                }
            }
        },300);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(getActivity(), SettingsActivity.class);
            startActivityForResult(intent, 0);
        }
        return super.onOptionsItemSelected(item);
    }


    public void onDestroy()
    {
        super.onDestroy();
        L.i("页面已onStop，需要停止轮询");
        loopRequestHandler.removeMessages(LOOP_WHAT);
    }


    @Override
    public void onRefresh() {
        initData();
        sms_refresh();
        mSwipRefreshLayout.setRefreshing(false);//关闭加载动画
    }
}